<template>
    <div class="chat-messages" ref="messagesContainer">
        <div class="messages-list">
            <ChatMessageItem
                v-for="message in messages"
                :key="message.id"
                :message="message"
                :is-streaming="message.isAnswer && message.id === currentStreamingAnswerId"
                @switch="$emit('switch', $event)"
                @refresh="$emit('refresh', $event)"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount, watch } from "vue";
import ChatMessageItem from "./ChatMessageItem.vue";

// 定义 props
const props = defineProps({
    messages: {
        type: Array,
        default: () => []
    },
    currentStreamingAnswerId: {
        type: String,
        default: ""
    }
});

// 定义 emits
const emit = defineEmits(['switch', 'refresh']);

// 消息容器引用
const messagesContainer = ref(null);

// 滚动相关状态
const autoScrollEnabled = ref(true);
const userScrollInterrupted = ref(false);
let scrollResumeTimer = null;

// 检查是否接近底部
function isNearBottom(el, threshold = 10) {
    if (!el) return true;
    return el.scrollHeight - el.scrollTop - el.clientHeight <= threshold;
}

// 处理滚动事件
function handleMessagesScroll() {
    const el = messagesContainer.value;
    if (!el) return;
    
    // 检查是否接近底部
    const nearBottom = isNearBottom(el);
    
    // 如果用户滚动离开底部，标记为介入状态
    if (!nearBottom && !userScrollInterrupted.value) {
        userScrollInterrupted.value = true;
        autoScrollEnabled.value = false;
        
        // 清除之前的定时器
        if (scrollResumeTimer) {
            clearTimeout(scrollResumeTimer);
        }
        
        // 设置5秒后恢复自动滚动
        scrollResumeTimer = setTimeout(() => {
            if (userScrollInterrupted.value) {
                userScrollInterrupted.value = false;
                autoScrollEnabled.value = true;
                // 如果当前有流式消息，立即滚动到底部
                if (props.currentStreamingAnswerId) {
                    scrollToBottom();
                }
            }
        }, 5000);
    }
    
    // 如果用户滚动回到底部，立即恢复自动滚动
    if (nearBottom && userScrollInterrupted.value) {
        userScrollInterrupted.value = false;
        autoScrollEnabled.value = true;
        if (scrollResumeTimer) {
            clearTimeout(scrollResumeTimer);
            scrollResumeTimer = null;
        }
    }
}

// 滚动到底部
const scrollToBottom = (force = false) => {
    nextTick(() => {
        const el = messagesContainer.value;
        if (!el) return;
        
        // 强制滚动或自动滚动开启时滚动
        const shouldAutoScroll = force || autoScrollEnabled.value;
        
        // 如果有流式消息且用户没有介入滚动，则自动滚动
        if (props.currentStreamingAnswerId && !userScrollInterrupted.value) {
            el.scrollTop = el.scrollHeight;
            return;
        }
        
        if (!shouldAutoScroll) return;
        el.scrollTop = el.scrollHeight;
    });
};

// 监听流式消息变化，自动滚动
watch(() => props.currentStreamingAnswerId, (newId) => {
    if (newId && !userScrollInterrupted.value) {
        scrollToBottom();
    }
});

// 监听消息变化，自动滚动
watch(() => props.messages, () => {
    if (props.currentStreamingAnswerId && !userScrollInterrupted.value) {
        scrollToBottom();
    }
}, { deep: true });

// 暴露滚动方法给父组件
defineExpose({
    scrollToBottom
});

// 组件挂载
onMounted(() => {
    scrollToBottom();
    if (messagesContainer.value) {
        messagesContainer.value.addEventListener("scroll", handleMessagesScroll, {
            passive: true,
        });
    }
});

// 组件卸载
onBeforeUnmount(() => {
    if (messagesContainer.value) {
        messagesContainer.value.removeEventListener("scroll", handleMessagesScroll);
    }
    // 清理定时器
    if (scrollResumeTimer) {
        clearTimeout(scrollResumeTimer);
        scrollResumeTimer = null;
    }
});
</script>

<style scoped lang="scss">
.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #fafafa;

    .messages-list {
        max-width: 800px;
        margin: 0 auto;
    }
}

// 滚动条样式
.chat-messages::-webkit-scrollbar {
    width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
    background: #d9d9d9;
    border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-track {
    background: #f0f0f0;
}
</style>
